package com.zhangyu.shadow.ec.pay;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.zhangyu.shadow.core.app.ConfigType;
import com.zhangyu.shadow.core.app.Shadow;
import com.zhangyu.shadow.core.delegate.ShadowDelegate;
import com.zhangyu.shadow.core.net.RestClient;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.ui.loader.ShadowLoader;
import com.zhangyu.shadow.core.weixin.ShadowWeChat;
import com.zhangyu.shadow.ec.R;

/**
 * @author zhangyu
 * @date 2017/11/22
 */

public class FastPay implements View.OnClickListener {
    private static final String TAG = "FastPay";
    private IPayResultListener mPayResultListener;
    private final Activity mActivity;
    private AlertDialog mAlertDialog;
    private int mOrderId;

    private FastPay(ShadowDelegate shadowDelegate) {
        mActivity = shadowDelegate.getProxyActivity();
        mAlertDialog = new AlertDialog.Builder(mActivity).create();
    }

    public static FastPay create(ShadowDelegate delegate) {
        return new FastPay(delegate);
    }

    public FastPay setPayResultListener(IPayResultListener listener) {
        mPayResultListener = listener;
        return this;
    }

    public FastPay setOrderId(int orderId) {
        mOrderId = orderId;
        return this;
    }

    public void beginPayDialog() {
        mAlertDialog.show();
        final Window window = mAlertDialog.getWindow();
        if (window != null) {
            window.setContentView(R.layout.dialog_pay);
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.anim_panel_up_from_bottom);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            //设置属性
            final WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            window.setAttributes(params);
            window.findViewById(R.id.btn_pay_cancel).setOnClickListener(this);
            window.findViewById(R.id.icon_ali_pay).setOnClickListener(this);
            window.findViewById(R.id.icon_wei_xin_pay).setOnClickListener(this);
        }
    }

    public final void aliPay(int orderId) {
        final String signUrl = "服务端支付地址" + orderId;
        //获取签名字符串
        RestClient.builder()
                .url(signUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final String paySign = JSON.parseObject(response).getString("result");
                        final PayAsyncTask payTask = new PayAsyncTask(mActivity, mPayResultListener);
                        payTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, paySign);
                    }
                })
                .build()
                .post();
    }

    public final void wxPay(int orderId) {
        ShadowLoader.stopLoading();
        final String prePayUrl = "服务端支付地址" + orderId;

        final IWXAPI iwxapi = ShadowWeChat.getInstance().getWXAPI();
        final String appId = Shadow.getConfiguration(ConfigType.WE_CHAT_APP_ID);
        iwxapi.registerApp(appId);
        RestClient.builder()
                .url(prePayUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final JSONObject result =
                                JSON.parseObject(response).getJSONObject("result");
                        final String prepayId = result.getString("prepayid");
                        final String partnerId = result.getString("partnerid");
                        final String packageValue = result.getString("package");
                        final String timestamp = result.getString("timestamp");
                        final String nonceStr = result.getString("noncestr");
                        final String paySign = result.getString("sign");

                        final PayReq payReq = new PayReq();
                        payReq.appId = appId;
                        payReq.prepayId = prepayId;
                        payReq.partnerId = partnerId;
                        payReq.packageValue = packageValue;
                        payReq.timeStamp = timestamp;
                        payReq.nonceStr = nonceStr;
                        payReq.sign = paySign;

                        iwxapi.sendReq(payReq);
                    }
                })
                .build()
                .post();
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.btn_pay_cancel) {

        } else if (id == R.id.icon_ali_pay) {
            aliPay(mOrderId);
        } else if (id == R.id.icon_wei_xin_pay) {
            wxPay(mOrderId);
        }
        mAlertDialog.cancel();
    }
}
